#include <iostream>
#include <stdlib.h>
#include <unistd.h>
using namespace std;

bool GetQueryString(string& query_string)
{
    bool result = false;
    string method = getenv("METHOD");
    // 标准输出被重定向了，用标准错误
    // 获取环境变量
    //cerr << "debug method:" << method << endl;
    if (method == "GET")
    {
        query_string = getenv("QUERY_STRING");
        cerr << "debug query_string:" << query_string << endl;
        return true;
    }
    else if (method == "POST")
    {
        // 如何知道读取多少个字节
        //cerr << "content-length:" << getenv("CONTENT_LENGTH") << endl;
        int content_length = atoi(getenv("CONTENT_LENGTH"));
        char c = 0;
        while (content_length)
        {
            read(0, &c, 1);
            query_string.push_back(c);
            content_length--;
        }
        //cerr << "post debug query_string:" << query_string << endl;
        return true;
    }
    else
    {
        return false;
    }
}

void CutString(string in, string sep, string& out1, string& out2)
{
    auto pos = in.find(sep);
    if (pos != string::npos)
    {
        out1 = in.substr(0, pos);
        out2 = in.substr(pos + sep.size());
    }
}

int main()
{
    string query_string;
    GetQueryString(query_string);
    // a=100&b=200
    string str1, str2;
    CutString(query_string, "&", str1, str2);

    string name1, value1;
    CutString(str1, "=", name1, value1);

    string name2, value2;
    CutString(str2, "=", name2, value2);    

    // cerr
    cerr << name1 << ":" << value1 << endl;
    cerr << name2 << ":" << value2 << endl;
    // 管道写入
    cout << name1 << ":" << value1 << endl;
    cout << name2 << ":" << value2 << endl; 

    // 可能计算，存储，搜索，注册登录等
    int x = atoi(value1.c_str());
    int y = atoi(value2.c_str());

    cout << "<html>";
    cout << "<head><meta charset=\"utf-8\"></head>";
    cout << "<body>";
    cout << "<h3>" << value1 << "+" << value2 << "=" << x + y << "</h3>";
    cout << "<h3>" << value1 << "-" << value2 << "=" << x - y << "</h3>";
    cout << "<h3>" << value1 << "*" << value2 << "=" << x * y << "</h3>";
    cout << "<h3>" << value1 << "/" << value2 << "=" << x / y << "</h3>";
    cout << "</body>";
    cout << "</html>";

    return 0;
}